//
//  ChargeDataSubmitController.m
//  Runone
//
//  Created by ekkaLyn on 2017/4/21.
//  Copyright © 2017年 runone. All rights reserved.
//

#import "ChargeDataSubmitController.h"
#import "AppDelegate.h"
#import "StationModel.h"
#import "EKPopMenuView.h"
#import "UIView+Addition.h"
#import "CJCalendarViewController.h"
#import "RequestHelper.h"
#import "RequestOutginseng.h"
#import "RequestGinsengModel.h"
#import "SVProgressHUD.h"
#import "BCNetAPIClient.h"
#import "NSDate+Extension.h"
#import "TollStationChargeListModel.h"
#import "MJExtension.h"
#import "EKCalendarView.h"

@interface ChargeDataSubmitController ()<CalendarViewControllerDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UIButton *stationDropBtn;
@property (assign, nonatomic) BOOL isSelectCanderBtn;
@property (weak, nonatomic) IBOutlet UIButton *datePickBtn;
@property (nonatomic, copy) NSMutableArray *stationNameArr;//收费站名
@property (nonatomic, copy) NSString *currenYDMStr;

@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;

@property (weak, nonatomic) IBOutlet UITextField *totalChargeTF;
@property (weak, nonatomic) IBOutlet UITextField *totalVehicleFlowTF;
//@property (assign, nonatomic) NSInteger stationIndex;
@property (nonatomic, strong)StationModel *model;
@property (nonatomic, strong) UIDatePicker *myDatePicker;
@property(nonatomic,strong)UIView*pickerView;
@property(nonatomic,strong)UIView*alphaView;


@end

@implementation ChargeDataSubmitController

#pragma   收费数据上报界面

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpNavigationBar];
    _confirmBtn.layer.cornerRadius = 5 ;
    _confirmBtn.layer.masksToBounds = YES;
    // self.navigationItem.title = @"收费数据上报";
    
    [self getStationData];
    [self configTF];
    _model = [[StationModel alloc] init];
   }

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    SendNotify(GLStationChargeReportNotification, self)
}
//设置标题
- (void)setUpNavigationBar{
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    UILabel *titleLabel            = [[UILabel alloc] init];
    titleLabel.size                = CGSizeMake(100, 30);
    titleLabel.text                = @"收费数据上报";
    titleLabel.textAlignment       = NSTextAlignmentCenter;
    titleLabel.textColor           = [UIColor whiteColor];
    self.navigationItem.titleView  = titleLabel;
    
}

- (void)awakeFromNib{
    [super awakeFromNib];
    //设置按钮圆角
    _confirmBtn.layer.cornerRadius = 5 ;
    _confirmBtn.layer.masksToBounds = YES;
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

- (void) getStationData {
    _stationNameArr = [[NSMutableArray alloc] init];
    AppDelegate *myDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
    for (StationModel *station in myDelegate.AllTollStationArray) {
        [_stationNameArr addObject:station.TollStationName];
    }
}

//输入框
- (void) configTF {
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(0, 0, 40, 30);
    label.textAlignment  = NSTextAlignmentRight;
    label.text = @"元";
    self.totalChargeTF.rightView = label;
    self.totalChargeTF.rightViewMode = UITextFieldViewModeAlways;
    
    UILabel *label2  = [[UILabel alloc] init];
    label2.frame = CGRectMake(0, 0, 40, 30);
    label2.text = @"车次";
    label2.textAlignment  = NSTextAlignmentRight;
    self.totalVehicleFlowTF.rightView = label2;
    self.totalVehicleFlowTF.rightViewMode =UITextFieldViewModeAlways;
}

//收费站名
- (IBAction)dropStationClick:(id)sender {
    AppDelegate *myDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
    EKPopMenuView *menuV = [[EKPopMenuView alloc] initEKPopViewWithFrame:CGRectMake(self.stationDropBtn.x, CGRectGetMaxY(self.stationDropBtn.frame), self.stationDropBtn.width, 44 * 5) annimationFormLeft:YES];
    menuV.itemNameArray = _stationNameArr ;
    menuV.itemH        = 44;
    menuV.fontSize      = 16.0f;
    menuV.fontColor     = [UIColor whiteColor];
    
    __weak __typeof(self)weakSelf = self;
    [menuV dismissHandler:^(BOOL isCanceled, NSInteger row) {
        if (!isCanceled) {
            weakSelf.model = myDelegate.AllTollStationArray[row];
            NSString *str = weakSelf.stationNameArr[row];
            [weakSelf.stationDropBtn setTitle:str forState:UIControlStateNormal];
            
        }else {
        
        }
    }];
    
    [menuV show];
}
//
- (IBAction)calendarBtnClick:(id)sender {
    [self setUpCalendaerVC];
    
}

//判断字符串是否是整型
- (BOOL)isPureInt:(NSString*)string{
    
    NSScanner* scan = [NSScanner scannerWithString:string];
    
    int val;
    
    return[scan scanInt:&val] && [scan isAtEnd];
    
}
//判断是否为浮点形：
- (BOOL)isPureFloat:(NSString*)string{
    
    NSScanner* scan = [NSScanner scannerWithString:string];
    
    float val;
    
    return[scan scanFloat:&val] && [scan isAtEnd];
    
}

//提交按钮
- (IBAction)comfirnBtnClick:(id)sender {
    //NSLog(@"%@",self.stationDropBtn.currentTitle);
    NSString *stationStr = self.stationDropBtn.currentTitle;
    NSString *dateStr    = self.datePickBtn.currentTitle;
    if ([stationStr compare:@"请选择收费站名"] == 0) {
        [SVProgressHUD showErrorWithStatus:@"请选择收费站名"];
        return;
    }
    if ([dateStr compare:@"请选择日期时间"] == 0) {
        [SVProgressHUD showErrorWithStatus:@"请选择日期时间"];
        return;
    }
    if (self.totalChargeTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"收费金额不能为空"];
        return;
    }
    if ([self.totalChargeTF.text containsString:@"."]){
        
        NSArray *arr = [self.totalChargeTF.text componentsSeparatedByString:@"."];
        NSString *str  = arr[0];
        if (str.length > 7) {
            [SVProgressHUD showErrorWithStatus:@"收费金额不能超过一千万元"];
            return;
        }
    }else {
        if (self.totalChargeTF.text.length > 7) {
            [SVProgressHUD showErrorWithStatus:@"收费金额不能超过一千万元"];
            return;
        }
    }
    
    if (self.totalVehicleFlowTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"出口车流量不能为空"];
        return;
    }
    if (![self isPureFloat:self.totalVehicleFlowTF.text]) {
        [SVProgressHUD showErrorWithStatus:@"出口车流量必须为整数"];
        return;
    }
    [self judgeTheDataIfExist];
}

#pragma mark - 拼接参数
-(NSString *)DataValueStationUId:(NSString *)stationUID chargeDate:(NSString *)chargeDate  {
    NSString *valueStr =[NSString stringWithFormat:                                          @"[{\"key\":\"TollStationUID\",\"value\":\"%@\"},                                         {\"key\":\"ChargeDate\",\"value\":\"%@\"}]",stationUID ,chargeDate];
    
    return valueStr;
}

//上报
- (void) judgeTheDataIfExist {
    if (!_model.TollStationUID) {
        [SVProgressHUD showErrorWithStatus:@"请先选择收费站"];
        return;
    }
    if (!_currenYDMStr) {
        [SVProgressHUD showErrorWithStatus:@"请先选择日期"];
        return;
    }
    
    [SVProgressHUD showWithStatus:@"正在上报..."];
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *getCurrentEventModel=[[RequestGinsengModel alloc] init];
    getCurrentEventModel.URL=GetEventDataURL;
    getCurrentEventModel.DataValue   = [self DataValueStationUId:_model.TollStationUID chargeDate:_currenYDMStr];
    getCurrentEventModel.UpdatedTime = @"";
    getCurrentEventModel.SystemCode  = @"GuangleHighway";
    getCurrentEventModel.MethodName  = @"TollStationChargeExists";
    [requestHelper RequestGinsengModel:getCurrentEventModel andPushController:self];
    requestHelper.block =^(RequestOutginseng *requestOutginseng,id dataValueModel){
        if ([requestOutginseng.Code isEqualToString:@"001"] ) {
            if ([requestOutginseng.DataValue boolValue]==YES) {
                [SVProgressHUD dismiss];
                NSString*alertMessage=[NSString stringWithFormat:@"%@已存在%@的收费数据,是否继续上报",_model.TollStationName,_currenYDMStr];
                
                UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"提示" message:alertMessage delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
                [alert show];
                
                return ;
            }else {
                [self postStationData];
            }
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:requestOutginseng.Message];
        }
        
        
    };
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==1) {
        [self postStationData];
    }
}

- (NSString *) configPostData {
    NSString *chargeStr ;
    if ([self.totalChargeTF.text containsString:@"."]){
        
        NSArray *arr = [self.totalChargeTF.text componentsSeparatedByString:@"."];
        NSString *str = arr[0];
        NSString *str1 = [arr[1] substringWithRange:NSMakeRange(0, 2)];
        chargeStr = [NSString stringWithFormat:@"%@.%@",str,str1];
    }else {
        chargeStr = self.totalChargeTF.text;
    }

    NSString *valueStr =[NSString stringWithFormat:@"[{\"key\":\"EMTollStationChargeInfo\",\"value\":\"{\\\"TollStationUID\\\":\\\"%@\\\",\\\"ChargeDate\\\":\\\"%@\\\",\\\"ChargeAmount\\\":\\\"%@\\\",\\\"ExportTrafficFlow\\\":\\\"%@\\\"}\"}]",_model.TollStationUID ,_currenYDMStr,chargeStr,self.totalVehicleFlowTF.text];
    
    return valueStr;
    
}

- (void) postStationData {
    
    [SVProgressHUD showWithStatus:@"正在上报..."];
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *getCurrentEventModel=[[RequestGinsengModel alloc] init];
    getCurrentEventModel.URL=GetEventDataURL;
    getCurrentEventModel.DataValue   = [self configPostData];
    getCurrentEventModel.UpdatedTime = @"";
    getCurrentEventModel.SystemCode  = @"GuangleHighway";
    getCurrentEventModel.MethodName  = @"ReportTollStationChargeInfo";
    [requestHelper RequestGinsengModel:getCurrentEventModel andPushController:self];
    requestHelper.block =^(RequestOutginseng *requestOutginseng,id dataValueModel){
        if ([requestOutginseng.Code isEqualToString:@"001"] ) {
            [SVProgressHUD showSuccessWithStatus:@"成功"];
            
            [self.navigationController popViewControllerAnimated:YES];
            
        }else {
            [SVProgressHUD showSuccessWithStatus:@"失败"];
        }
        
        
    };
    [requestHelper RequestGinsengModel:getCurrentEventModel andPushController:self];
}

#pragma mark - 日历

- (void) setUpCalendaerVC {
    
    EKCalendarView *calendar = [[EKCalendarView alloc] initWithDatePosition:EKCalendarMiddel CompleteBlock:^(NSDate *startDate) {
        if (startDate != nil) {
            _currenYDMStr = [startDate stringWithFormat:@"yyyy-MM-dd"];
            NSArray*dateArray= [_currenYDMStr componentsSeparatedByString:@"-"];
            NSString *yDMStr = [NSString stringWithFormat:@"%@年%@月%@日",dateArray[0],dateArray[1],dateArray[2]];
            [self.datePickBtn setTitle:yDMStr forState:UIControlStateNormal];
        }
//        [self setUpShowDate:yDMStr];        self.isSelectCanderBtn = NO;
//        [self loadNewData];
        
    }];
    [calendar dismissHandler:^(BOOL isCanceled) {
       self.isSelectCanderBtn = NO;
    }];
    [calendar show];
    
//    UIWindow*window=[UIApplication sharedApplication].windows[0];
//    if (!self.alphaView) {
//        self.alphaView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, window.bounds.size.width, window.bounds.size.height)];
//        self.alphaView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
//        
//        [window addSubview:self.alphaView];
//        
//        
//        
//        self.pickerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width-100, 280)];
//        self.pickerView.center = self.view.center;
//        self.pickerView.backgroundColor=[UIColor whiteColor];
//        [self.alphaView addSubview:self.pickerView];
//        
//        self.myDatePicker = [[UIDatePicker alloc] init];
//        self.myDatePicker.frame=CGRectMake(10, 10, self.view.bounds.size.width-120, 250);
//        self.myDatePicker.datePickerMode = UIDatePickerModeDate;
//        [self.myDatePicker setLocale:[NSLocale localeWithLocaleIdentifier:@"zh-CN"]];
//        [self.pickerView addSubview:self.myDatePicker];
//        
//        [self.myDatePicker addTarget:self
//                              action:@selector(datePickerDateChanged:)
//                    forControlEvents:UIControlEventValueChanged];
//        
//        NSTimeInterval minYearTime = -365 * 24 * 60 * 60;
//        NSTimeInterval maxYearTime = -1 * 24 * 60 * 60;
//        NSDate *todayDate = [NSDate date];
//        NSDate *oneYearFromToday = [todayDate dateByAddingTimeInterval:minYearTime];
//        NSDate *twoYearsFromToday = [todayDate dateByAddingTimeInterval:maxYearTime];
//        self.myDatePicker.minimumDate = oneYearFromToday;
//        self.myDatePicker.maximumDate = twoYearsFromToday;
//        
//        UIButton*cancelBtn=[UIButton buttonWithType:UIButtonTypeCustom];
//        cancelBtn.frame=CGRectMake(20, 240, 80, 30);
//        [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
//        cancelBtn.layer.cornerRadius=3;
//        [cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        cancelBtn.layer.borderColor=[UIColor blackColor].CGColor;
//        cancelBtn.layer.borderWidth=0.5;
//        [cancelBtn addTarget:self action:@selector(canclePickerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//        [self.pickerView addSubview:cancelBtn];
//        
//        UIButton*sureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
//        sureBtn.frame=CGRectMake(self.pickerView.bounds.size.width-100, 240, 80, 30);
//        [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
//        [sureBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        sureBtn.layer.cornerRadius=3;
//        sureBtn.layer.borderColor=[UIColor blackColor].CGColor;
//        sureBtn.layer.borderWidth=0.5;
//        [sureBtn addTarget:self action:@selector(surePickerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//        [self.pickerView addSubview:sureBtn];
//        
//    }
//    else
//    {
//        [window addSubview:self.alphaView];
//    }
    
}

-(void)canclePickerBtnClick:(UIButton*)btn
{
    [self.alphaView removeFromSuperview];
}

-(void)surePickerBtnClick:(UIButton*)btn
{
    NSDateFormatter*dateFormatter=[[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    _currenYDMStr =[dateFormatter stringFromDate:self.myDatePicker.date];
    NSArray*dateArray= [_currenYDMStr componentsSeparatedByString:@"-"];
    NSString *yDMStr = [NSString stringWithFormat:@"%@年%@月%@日",dateArray[0],dateArray[1],dateArray[2]];
    [self.datePickBtn setTitle:yDMStr forState:UIControlStateNormal];
    [self.alphaView removeFromSuperview];
}

- (void) datePickerDateChanged:(UIDatePicker *)paramDatePicker {
    if ([paramDatePicker isEqual:self.myDatePicker]) {
        NSLog(@"Selected date = %@", paramDatePicker.date);
    }
}




@end
